// NOTE: this prototype extension is courtesy of http://www.agileweb.org/articles/2006/07/28/onload-final-update

Object.extend(Event, {
  observe: function(element, name, observer, useCapture) {
    var element = $(element);
    useCapture = useCapture || false;
    if (name == 'keypress' && (navigator.appVersion.match(/Konqueror|Safari|KHTML/) || element.attachEvent)) name = 'keydown';
    if (name == 'load' && element.screen) this._observeLoad(element, name, observer, useCapture);
    else this._observeAndCache(element, name, observer, useCapture);
  },
  _observeLoad : function(element, name, observer, useCapture) {
    if (!this._readyCallbacks) {
      var loader = this._onloadWindow.bind(this);
      if (document.addEventListener) document.addEventListener("DOMContentLoaded", loader, false);
      /*@cc_on @*/
      /*@if (@_win32)
         if (! $("__ie_onload")) {
	            document.write("<script id='__ie_onload' defer='true' src='javascript:void(0)'><\/script>");
            var script = $("__ie_onload");
            script.onreadystatechange = function() { if (this.readyState == "complete") loader(); };
        } else {
            loader();
        }
      /*@end @*/
      if (navigator.appVersion.match(/Konqueror|Safari|KHTML/i)) Event._timer = setInterval(function() { if (/loaded|complete/.test(document.readyState))loader();}, 10);
      Event._readyCallbacks =  [];
      this._observeAndCache(element, name, loader, useCapture);
    }
    Event._readyCallbacks.push(observer);
  },
  _onloadWindow : function() {
    if (arguments.callee.done) return;
    arguments.callee.done = true;
    if (this._timer) clearInterval(this._timer);
    this._readyCallbacks.each(function(f) { f() });
    this._readyCallbacks = null;
  }
});


/* ======================================================================== */

/* NOTE: the following code was extracted from the UFO source */

/* Unobtrusive Flash Objects (UFO) v3.20 <http://www.bobbyvandersluis.com/ufo/>
	Copyright 2005, 2006 Bobby van der Sluis
	This software is licensed under the CC-GNU LGPL <http://creativecommons.org/licenses/LGPL/2.1/>
*/

var UFO = {
	ua: navigator.userAgent.toLowerCase(),
		
	createCSS: function(selector, declaration) {
		var _h = document.getElementsByTagName("head")[0]; 
		var _s = this.createElement("style");
		if (!this.uaHas("ieWin")) _s.appendChild(document.createTextNode(selector + " {" + declaration + "}")); // bugs in IE/Win
		_s.setAttribute("type", "text/css");
		_s.setAttribute("media", "screen"); 
		_h.appendChild(_s);
		if (this.uaHas("ieWin") && document.styleSheets && document.styleSheets.length > 0) {
			var _ls = document.styleSheets[document.styleSheets.length - 1];
			if (typeof _ls.addRule == "object") _ls.addRule(selector, declaration);
		}
	},
	
	createElement: function(el) {
		return (this.uaHas("xml") && typeof document.createElementNS != "undefined") ?  document.createElementNS("http://www.w3.org/1999/xhtml", el) : document.createElement(el);
	},

	uaHas: function(ft) {
		var _u = this.ua;
		switch(ft) {
			case "xml":
				var _m = document.getElementsByTagName("meta");
				var _l = _m.length;
				for (var i = 0; i < _l; i++) {
					if (/content-type/i.test(_m[i].getAttribute("http-equiv")) && /xml/i.test(_m[i].getAttribute("content"))) return true;
				}
				return false;
			case "ieWin": return /msie/.test(_u) && !/opera/.test(_u) && /win/.test(_u);
			case "ieWin7": return /msie 7/.test(_u) && !/opera/.test(_u) && /win/.test(_u); /* NOTE: added by JB 2006-09-20 */
			default: return false;
		}
	}
};


/* ======================================================================== */


/* the object that takes care of toggling the elements in the top-content area */
var JAMATopContent = {
  toggle : function (event) {
		// prevent the browser from following the link
		Event.stop(event);

		// loop through all the top content items, deactivating all sections (no checking needed)
		$$('#top-content .Item').each(function(item){ item.removeClassName('Active'); });

		// 'activate' the section
		Event.element(event).parentNode.parentNode.addClassName('Active');

		// get rid of the browser's dotted line indicating focus
		Event.element(event).blur();
	} // END: toggle()

}; // END: JAMATopContent


/* ======================================================================== */


/* the ColumnSet constructor */
function ColumnSet(column_list, custom) {
  // the list of columns
  this.column_list = column_list;

//  this.custom = custom;
  var custom = custom;

  this.fix = function() {
    // find the max height
    var max_height = this.column_list.max(function(column) {
      var cumulative_height = (column['exclude_height_in_cumulative']) ? 0 : column['css_fix']; /* gotta love exceptions to the rule */
      column['elements'].each(function(element) {
        cumulative_height += $(element).offsetHeight;
      });
      return cumulative_height;
    });

    var height_prop_name = (((UFO.uaHas("ieWin") && !UFO.uaHas("ieWin7")) ? "" : "min-") + "height");

    // this calculates the height of the column minus the last element (the one we're going to adjust)
    this.column_list.each(function(column) {
      var height_excluding_last = column['css_fix'] + 12;

      for(var i=0; i < (column['elements'].length - 1); i++) {
        height_excluding_last += $(column['elements'][i]).offsetHeight;
      }

      /* NOTE: this is ugly */
      if (column['exclude_height_in_cumulative']) {
        UFO.createCSS('.JAMAHome #top-content .Item UL', (((UFO.uaHas("ieWin") && !UFO.uaHas("ieWin7")) ? "" : "min-") + "height") + ": " + (max_height - height_excluding_last) + "px");
      } else {
        /* NOTE: i had to do this because the property name we're setting needs to be a string */
        if ( UFO.uaHas("ieWin") && !UFO.uaHas("ieWin7") ) {
          $$(column['element_to_adjust'])[0].setStyle({ "height" : (max_height - height_excluding_last - (custom ? 0 : column['css_fix'])) + "px" });
        } else {
          $$(column['element_to_adjust'])[0].setStyle({ "min-height" : (max_height - height_excluding_last - (custom ? 0 : column['css_fix'])) + "px" });
        }
      }

    });

  };
} // END: ColumnSet constructor


/* the height fixer object */
var JAMAHeightFixer = {
  groups : {
    'main content area' : new ColumnSet([
      { elements : ['clinician-corner', 'author-in-the-room'], element_to_adjust : '#author-in-the-room .BoxFix', css_fix : (29 + 15) }
,     { elements : ['podcast', 'patient-page', 'video-news-release'], element_to_adjust : '#video-news-release .BoxFix', css_fix : (29 + 15) }
,     { elements : ['top-content'], element_to_adjust : '#most-viewed-articles', css_fix : (126), exclude_height_in_cumulative: true }
    ], true)

,   'bottom grey boxes' : new ColumnSet([
      { elements : ['stay-connected'], element_to_adjust : '#stay-connected .BoxFix', css_fix : 18 }
,     { elements : ['call-for-papers'], element_to_adjust : '#call-for-papers .BoxFix', css_fix : 18 }
    ])
  } // END: element sets

, fixAll : function() {
    for (var group in this.groups) {
      this.groups[group].fix();
    }
  } // END: fixAll()

, fix : function(group) {
    this.groups[group].fix();
  } // END: fix()

}; // END: JAMAHeightFixer


/* ======================================================================== */


// add on onload event for the window
Event.observe(window, 'load', function(){
	// loop through all the top content items and attach the onclick event handler to the anchor
	$$('#top-content H2 A').each(function(anchor){
		Event.observe(anchor, 'click', JAMATopContent.toggle, false);
		anchor.onclick = function(){ return false; }; // fix for dumb older versions of safari
	});

	// fix the box heights
//	JAMAHeightFixer.fixAll();
}, false);


// add on onresize event to fix the box heights
/* NOTE: this function crashes IE/win < 7 */
if ( !(UFO.uaHas("ieWin") && !UFO.uaHas("ieWin7")) ) {
	Event.observe(window, 'resize', function(){
//		JAMAHeightFixer.fixAll();
	}, false);
}
